'''Copyright 2010 Giordano Tamburrelli. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
3. Neither the name of Giordano Tamburrelli nor the names of his contributors may be used
   to endorse or promote products derived from this software without specific
   prior written permission.
   
THIS SOFTWARE IS PROVIDED BY GIORDANO TAMBURRELLI "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL GIORDANO TAMBURRELLI OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE.

Created on May 24, 2010

@author: Giordano Tamburrelli
'''

import re
import string
from DBLP.Utils import ends_with

def url_handler_factory(url):
    if ends_with(url, '.pdf'):
        handler = PaperURLHandler
    else:
        from DBLP.Editors import get_editor, EDITORS
        editor = get_editor(url)
        try:
            handler = EDITORS[editor]
        except KeyError:
            return None
    return handler
        
class AbstractURLHandler():
    def __init__(self, verbose = True):
        pass
    
class PaperURLHandler(AbstractURLHandler):
    def get_paper(self, url, url_opener):
        pdf = url_opener.get_page(url).read()
        return pdf

class AcmURLHandler(AbstractURLHandler):
    def get_paper(self, url, url_opener):
        prefix = 'ft_gateway.cfm'
        html = url_opener.get_page(url).read()
        exp = re.compile(prefix+'.*?"')
        pdf_url = exp.findall(html)
        if pdf_url.__len__() != 1:
            return None
        pdf_url = string.rstrip(pdf_url[0], '"')
        pdf_url = 'http://portal.acm.org/' + pdf_url
        pdf = url_opener.get_page(url = pdf_url).read()
        return pdf
    
class ScienceURLHandler(AbstractURLHandler):
    def get_paper(self, url, url_opener):
        prefix = '<li class="featureCount">\n+<a href="'
        html = url_opener.get_page(url).read()
        exp = re.compile(prefix+'.*?\.pdf')
        pdf_url = exp.findall(html)
        if pdf_url.__len__() != 1:
            return None
        pdf_url = string.rstrip(pdf_url[0], '"')
        pdf_url = pdf_url['<li class="featureCount">\n<a href="'.__len__():pdf_url.__len__()]
        pdf = url_opener.get_page(url = pdf_url).read()
        return pdf
    
class DoiURLHandler(AbstractURLHandler):
    def get_paper(self, url, url_opener):
        url = url_opener.get_page(url).geturl()
        handler = url_handler_factory(url)
        if handler != None:
            handler = handler()
            if isinstance(handler, DoiURLHandler):
                return None
            return handler.get_paper(url, url_opener)
        else: return None
        
class CrossRefHandler(AbstractURLHandler):
    def get_paper(self, url, url_opener):
        html = url_opener.get_page(url).read()
        exp = re.compile('http://ieeexplore\.ieee\.org/.+?"')
        pdf_url = exp.findall(html)
        if pdf_url.__len__() != 1:
            return None
        pdf_url = string.rstrip(pdf_url[0], '"')
        handler = url_handler_factory(pdf_url)
        if handler != None:
            handler = handler()
            return handler.get_paper(pdf_url, url_opener)
        else: return None 

class ComputerHandler(AbstractURLHandler):
    def get_paper(self, url, url_opener):
        html = url_opener.get_page(url).read()
        exp = re.compile('class="abs\-xplore">\n<a href=".+?"')
        pdf_url = exp.findall(html)
        if pdf_url.__len__() != 1:
            return None
        pdf_url = pdf_url[0]
        pdf_url = pdf_url['class="abs-xplore">.<a href="'.__len__():pdf_url.__len__()-1]
        handler = url_handler_factory(pdf_url)
        if handler != None:
            handler = handler()
            return handler.get_paper(pdf_url, url_opener)
        else: return None    

class DoiComputerHandler(AbstractURLHandler):
    def get_paper(self, url, url_opener):
        html = url_opener.get_page(url).read()
        exp = re.compile('<a target="_blank" href="http://doi\.ieeecomputersociety\.org/.+?"')
        pdf_url = exp.findall(html)
        if pdf_url.__len__() != 1:
            return None
        pdf_url = pdf_url[0]
        pdf_url = pdf_url["<a target=\"_blank\" href=\"".__len__():pdf_url.__len__()-1]
        handler = url_handler_factory(pdf_url)
        if handler != None:
            handler = handler()
            return handler.get_paper(pdf_url, url_opener)
        else: return None    
        
class DoiIEEEHandler(AbstractURLHandler):
    def get_paper(self, url, url_opener):
        url = url.replace('doi.ieeecomputersociety.org', 'dx.doi.org')
        handler = url_handler_factory(url)
        if handler != None:
            handler = handler()
            return handler.get_paper(url, url_opener)
        else: return None
        
class IeeeURLHandler(AbstractURLHandler):
    def get_paper(self, url, url_opener):
        prefix = 'http://ieeexplore.ieee.org/stampPDF/getPDF.jsp?tp=&' 
        exp = re.compile('arnumber=\d+')
        pdf_url = exp.findall(url)
        if pdf_url.__len__() != 1:
            return None
        pdf_url = pdf_url[0]
        url = prefix + pdf_url
        pdf = url_opener.get_page(url = url).read()
        return pdf
    
    
class SpringerURLHandler(AbstractURLHandler):
    def get_paper(self, url, url_opener):
        prefix = 'http://www.springerlink.com'
        html = url_opener.get_page(url).read()
        exp = re.compile('/content/.+/fulltext.pdf'+'.*?"')
        pdf_url = exp.findall(html)
        if pdf_url.__len__() != 1:
            return None
        pdf_url = string.rstrip(pdf_url[0], '"')
        pdf_url  = prefix + pdf_url
        pdf = url_opener.get_page(url = pdf_url).read()
        return pdf
    
    
class EceasstURLHandler(AbstractURLHandler):
    def get_paper(self, url, url_opener):
        prefix = 'http://journal.ub.tu-berlin.de/index.php/eceasst/article/view/\d+/\d+'
        html = url_opener.get_page(url).read()
        exp = re.compile(prefix+'.*?" class="action"')
        pdf_url = exp.findall(html)
        if pdf_url.__len__() != 1: 
            return None
        pdf_url = string.rstrip(pdf_url[0], '" class="action"')
        pdf_url = pdf_url.lstrip('http://journal.ub.tu-berlin.de/index.php/eceasst/article/view/')
        pdf_url = 'http://journal.ub.tu-berlin.de/index.php/eceasst/article/download/' + pdf_url
        pdf = url_opener.get_page(pdf_url).read()
        return pdf
    
class JucsHandler(AbstractURLHandler):
    def get_paper(self, url, url_opener):
        prefix = 'http://www.jucs.org/'
        html = url_opener.get_page(url).read()
        exp = re.compile('<a href="/jucs_9_7/.*?\.pdf')
        pdf_url = exp.findall(html)
        if pdf_url.__len__() != 1: 
            return None
        pdf_url = pdf_url[0].lstrip('<a href="/')
        pdf_url = prefix + pdf_url
        pdf = url_opener.get_page(pdf_url).read()
        return pdf
    
class InterScienceHandler(AbstractURLHandler):
    def get_paper(self, url, url_opener):
        prefix = 'http://download.interscience.wiley.com/cgi-bin/fulltext?ID='
        postfix = '&PLACEBO=IE.pdf&mode=pdf'
        html = url_opener.get_page(url).read()
        exp = re.compile('/cgi-bin/fulltext/.*?/')
        pdf_url = exp.findall(html)
        if pdf_url.__len__() != 1: 
            return None
        pdf_url = pdf_url[0].rstrip('/')
        pdf_url = pdf_url.lstrip('/cgi-bin/fulltext/')
        pdf_url = prefix + pdf_url + postfix
        pdf = url_opener.get_page(pdf_url).read()
        return pdf
